// 数据库新增
async function addData(collection, data) {
  try {
    const db = uniCloud.database() // 获取数据库实例
    const res = await db.collection(collection).add(data) // 在指定集合中添加数据
    console.log('🚀 ~ file: cloudUtils.js:10 ~ addData ~ res:', res,data)
    return {
      code: 0,
      msg: '添加记录成功',
      ...res,
    }
  } catch (err) {
    throw new Error('添加记录失败：' + err.message)
  }
}
// 从数据库获取数据
async function getData(collection, options = {}) {
  try {
    const db = uniCloud.database()
    let query = db.collection(collection)

    // 添加查询条件
    if (options.condition) {
      query = query.where(options.condition)
    }

    // 添加排序选项
    if (options.orderByField && options.orderByDirection) {
      query = query.orderBy(options.orderByField, options.orderByDirection)
    }

    // 添加查询条数限制
    if (options.limit) {
      query = query.limit(options.limit)
    }

    const res = await query.get()
    console.log('🚀 ~ file: cloudUtils.js:10 ~ getData ~ res:', res)

    return {
      code: 0,
      msg: '获取记录成功',
      data: res.result.data,
    }
  } catch (err) {
    throw new Error('获取记录失败：' + err.message)
  }
}
// 更新数据库
async function updateData(collection, data) {
  try {
    const db = uniCloud.database()
    const { _id, ...updateData } = data;
    console.log("🚀 ~ file: cloudUtils.js:54 ~ updateData ~ data:", data)
    const res = await db.collection(collection).doc(_id).update(updateData)
    console.log('🚀 ~ file: cloudUtils.js:10 ~ updateData ~ res:', res)
    return {
      code: 0,
      msg: '更新记录成功',
      ...res,
    }
  } catch (err) {
    throw new Error('更新记录失败：' + err.message)
  }
}


// 封装统一的操作函数
export function performOperation(operation, collection, data, limit) {
  return new Promise((resolve, reject) => {
    let promise
    if (operation === 'add') {
      promise = addData(collection, data)
    } else if (operation === 'get') {
      promise = getData(collection, data, limit)
    } else if (operation === 'update') {
      promise = updateData(collection, data)
    } else {
      reject(new Error('Invalid operation'))
    }

    promise
      .then((res) => {
        resolve(res)
      })
      .catch((err) => {
        console.log(err, 'err')
        reject(err)
      })
  })
}
